<template>


    <div class="page-box">
       <div class="page-title">
          {{ '仓库管理' }}
       </div>
       <div class="page-search">
          <div class="search-box" :style="{ height: IsHeight }">
             <el-input v-model="searchKeyword" placeholder="搜索仓库名称/编号/人员/地址（支持子库搜索）" @input="handleSearch"
                style="width: 280px; margin-right: 10px; margin-bottom: 10px;" clearable>
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
             </el-input>
          </div>
          <div class="search-btn">
             <div class="btn_item" @click="handleClickHeight">
                <img class="btn_img" src="../../../assets/sx.png" alt=""> <span> 高级筛选 </span>
             </div>
             <div class="btn_item">
                <img class="btn_img" src="../../../assets/dc.png" alt=""> <span> 导出 </span>
             </div>
          </div>
       </div>
       <div class="search-btn-right">
          <el-button color="#626aef" type="primary" @click="handleClickAdd('main')"> 新增仓库 </el-button>
       </div>
    </div>
 
    <!-- 搜索结果提示 -->
    <!-- <div v-if="searchKeyword.trim()" class="search-result-tip">
       <el-icon><Search /></el-icon>
       <span>搜索 "{{ searchKeyword }}" 的结果，共找到 {{ tabeData.length }} 个仓库</span>
       <el-button type="text" @click="clearSearch" style="margin-left: 10px;">清除搜索</el-button>
    </div> -->

    <div class="table-box">
       <el-table  :data="tabeData" style="width: 100%" v-loading="loading" border
          :row-class-name="tableRowClassName"  default-expand-all     row-key="id">
          <el-table-column align="center" fixed prop="rowNumber" label="" width="60" />
          <el-table-column align="center" prop="name" label="仓库名称" width="180">
            <template #default="scope">
              <div v-if="scope.row.parent_id">
                <span>{{ scope.row.name }}</span>
              </div>
              <div v-else class="main-warehouse">
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="code" label="仓库编号" width="120" />
          <el-table-column align="center" prop="type" label="仓库类型" width="120" >
            <template #default="scope">
              <span>{{ scope.row.type === 1 ? '主仓库' : '子仓库' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="manager_name" label="库管人员名称" width="120" />
          <el-table-column align="center" prop="manager_phone" label="库管人员电话" width="120" />
               
          <el-table-column align="center" prop="address" label="详细地址" width="150" />
          <el-table-column align="center" prop="note" label="备注" min-width="150">
            <template #default="scope">
              <div>{{ scope.row.note }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="creator_name" label="创建人姓名" width="100" />
          <el-table-column align="center" prop="created_at" label="创建时间" width="180" />
          <el-table-column fixed="right" label="操作" width="230" align="center">
             <template #default="scope">
                <div class="btn-box">
                   <el-button plain size="small" type="primary" @click="handleClickEdit(scope.row)">编辑</el-button>
                   <el-button v-if="!scope.row.parent_id" 
                      plain size="small" type="success" @click="handleClickAdd('sub', scope.row)">添加子库</el-button>
                  
                   <el-button plain size="small" type="primary" @click="handleClickDetails(scope.row)">详情</el-button>
                </div>
             </template>
          </el-table-column>
       </el-table>
    </div>
 
    <!-- 分页 -->
    <Pagination class="pagination" @pageSize="pageSize" @getPage="getPage" :page="pageData.page"
       :page-size="pageData.page_size" :total="total" />
    <Dialog v-model:dialogVisible="isShow" :dialogType="dialogType" :dialogRow="dialogRow" @submit="handleSubmit" />
    <WarehouseDetails v-model:dialogVisible="DetailsVisible" :dialogRow="dialogRow" @submit="handleSubmit" />
 </template>
 
 <script setup lang="ts">
 import { ref, onMounted, watch } from "vue";
 import Pagination from "@/components/Pagination.vue";
 import { ElMessageBox, ElMessage } from 'element-plus';
 import { Search } from '@element-plus/icons-vue';
 import api from "@/api";
 import Dialog from "./components/dialog.vue";
 import WarehouseDetails from "./components/WarehouseDetails.vue";
 // 定义仓库数据类型
 interface Warehouse {
    id: string | number;
    name: string;
    code: string;
    type?: number;
    manager_name?: string;
    manager_phone?: string;
    city?: string;
    area?: string;
    address?: string;
    service_items?: string;
    note?: string;
    parent_id?: string | number;
    parent_name?: string;
    children?: Warehouse[];
    creator_name?: string;
    creator_admin_id?: string;
    created_at?: string;
    rowNumber?: number;
    manager_member_id?: string;
 }
 const DetailsVisible = ref<boolean>(false);

 let IsHeight = ref<number | string>(0);
 const isShow = ref<boolean>(false);
 let dialogType = ref<string>('');
 let dialogRow = ref<Warehouse>({} as Warehouse);
 const pageData = ref({
    page_size: 10,
    page: 1,
 });
 const total = ref(0);
 const tabeData = ref<Warehouse[]>([]);
 const originalData = ref<Warehouse[]>([]); // 存储原始数据
 const searchKeyword = ref<string>(''); // 搜索关键词
 // 侦听动态分页
 watch(
    () => pageData.value.page,
    () => {
       getAlltabeData();
    }
 );

 watch(
    () => pageData.value.page_size,
    () => {
       getAlltabeData();
    }
 );


 let nub = ref<number>(0);
 const handleClickHeight = () => {
    nub.value++;
    if (nub.value % 2 == 1) {
       IsHeight.value = '40px';
    } else {
       IsHeight.value = '0px';
    }
 }
 
 const pageSize = (e: number) => {
    pageData.value.page_size = e;
    getAlltabeData();
 }
 const getPage = (e: number) => {
    pageData.value.page = e;
    getAlltabeData();
 }
 
 onMounted(() => {
    getAlltabeData();
 })
 
 // 设置行样式
 const tableRowClassName = ({ row }: { row: Warehouse }) => {
    if (row.parent_id) {
      return 'sub-warehouse-row';
    }
    return '';
 };
 
 // 获取仓库列表
 const getAlltabeData = async () => {
    loading.value = true;
    try {
      const res = await api.product.warehouse_list({
        page_size: pageData.value.page_size,
        page: pageData.value.page,
      });

      if (res.code == 200 && res.data.length > 0) {
        originalData.value = res.data || [];
        // 如果有搜索关键词，执行搜索
        if (searchKeyword.value.trim()) {
          performSearch();
        } else {
          tabeData.value = originalData.value;
        }
      }
    } catch (error) {
      console.error('获取仓库列表失败', error);
    } finally {
      loading.value = false;
    }
 };
 
 const loading = ref(false);


 // 搜索处理函数（带防抖）
 let searchTimer: NodeJS.Timeout | null = null;
 const handleSearch = () => {
    // 清除之前的定时器
    if (searchTimer) {
      clearTimeout(searchTimer);
    }

    // 设置新的定时器，300ms后执行搜索
    searchTimer = setTimeout(() => {
      if (searchKeyword.value.trim()) {
        performSearch();
      } else {
        // 如果搜索框为空，显示所有数据
        tabeData.value = originalData.value;
      }
    }, 300);
 };

 // 执行搜索
 const performSearch = () => {
    const keyword = searchKeyword.value.trim().toLowerCase();
   //  如果没有执行搜索则显示所有数据
    if (!keyword) {
      tabeData.value = originalData.value;
      return;
    }
// 遍历数据，检查主仓库和子仓库是否匹配
    const filteredData: Warehouse[] = [];

    originalData.value.forEach((mainWarehouse: Warehouse) => {
      // 检查主仓库是否匹配
      const mainMatches = isWarehouseMatch(mainWarehouse, keyword);

      // 检查子仓库是否有匹配的
      const matchedChildren: Warehouse[] = [];
      if (mainWarehouse.children && mainWarehouse.children.length > 0) {
        mainWarehouse.children.forEach((child: Warehouse) => {
          if (isWarehouseMatch(child, keyword)) {
            matchedChildren.push(child);
          }
        });
      }

      // 如果主仓库匹配或有子仓库匹配，则添加到结果中
      if (mainMatches || matchedChildren.length > 0) {
        const warehouseToAdd = { ...mainWarehouse };

        if (matchedChildren.length > 0) {
          // 如果有匹配的子仓库，只显示匹配的子仓库
          warehouseToAdd.children = matchedChildren;
        }

        filteredData.push(warehouseToAdd);
      }
    });

    tabeData.value = filteredData;
 };

 // 检查仓库是否匹配搜索关键词
 const isWarehouseMatch = (warehouse: Warehouse, keyword: string): boolean => {
    return !!(
      warehouse.name?.toLowerCase().includes(keyword) ||
      warehouse.code?.toLowerCase().includes(keyword) ||
      warehouse.manager_name?.toLowerCase().includes(keyword) ||
      warehouse.manager_phone?.toLowerCase().includes(keyword) ||
      warehouse.address?.toLowerCase().includes(keyword) ||
      warehouse.note?.toLowerCase().includes(keyword)
    );
 };
 
 // 添加仓库
 const handleClickAdd = (type: 'main' | 'sub', parentRow: Warehouse | null = null) => {
    dialogType.value = type === 'main' ? 'add' : 'addSub';
    dialogRow.value = type === 'main' ? {} as Warehouse : { 
       parent_id: parentRow?.id, 
       parent_name: parentRow?.name 
    } as Warehouse;
    isShow.value = true;
 }
 
 // 编辑仓库
 const handleClickEdit = (row: Warehouse) => {
    dialogType.value = row.parent_id ? 'editSub' : 'edit';
    dialogRow.value = { ...row } as Warehouse;
    isShow.value = true;
 }
 
 // 删除仓库
 const handleClickDelete = (row: Warehouse) => {
    ElMessageBox.confirm(
      `确定要删除${row.parent_id ? '子' : ''}仓库"${row.name}"吗？${!row.parent_id && row.children && row.children.length > 0 ? '删除后将同时删除其下所有子仓库。' : ''}`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      try {
        // 这里调用删除API
        const res = await api.parking.delete(row.id);
        if (res.code === 0) {
          ElMessage.success('删除成功');
          getAlltabeData();
        } else {
          ElMessage.error(res.msg || '删除失败');
        }
      } catch (error) {
        ElMessage.error('删除失败');
      }
    }).catch(() => {});
 }
 
 // 提交表单回调
 const handleSubmit = () => {
    getAlltabeData();
 }

 // 详情
 const handleClickDetails = async (row: Warehouse) => {
    const res = await api.product.warehouse_detail({
      id: row.id
    });
    if (res.code == 200) {
      dialogRow.value = res.data;
      console.log(dialogRow.value, 'dialogRow.value');
      DetailsVisible.value = true;
    }
 }
 
 
 </script>
 
 <style lang="scss" scoped>
 .btn-box {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap: 5px;
 }
 
 .main-warehouse {
    font-weight: bold;
    color: #333;
 }

 // 搜索结果提示样式
 .search-result-tip {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    margin-bottom: 16px;
    background-color: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 6px;
    color: #0369a1;
    font-size: 14px;

    .el-icon {
       margin-right: 8px;
       color: #0284c7;
    }
 }
 
 // 输入框样式
 :deep(.el-input__wrapper) {
    background-color: rgba(250, 252, 251, 1);
 }
 
 //表格样式
 :deep(.el-table) {
    --el-table-header-bg-color: rgba(235, 236, 240, 1);
 }
 
 :deep(.el-table thead) {
    color: #444;
 }
 
 // 子仓库行样式
 :deep(.sub-warehouse-row) {
    background-color: #fef6e5;
 }
 
 //分页样式
 .pagination {
    width: calc(100% - 250px);
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding-top: 10px;
    border-top: 1px solid #98989848;
 }
 
 :deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: #000 !important;
 }
 </style>
 